package com.google.code.sysarch.v2.v2_final;

import java.awt.Graphics2D;

public class Elf extends Thread implements Drawable {
	
	static int elvesNeeded = 4;
	static int elvesWaiting = 0;
	static boolean elvesReleased = false;
	static int elvesTotal = 0;
	
	Sprite sprite;
	PathWalker myWalker;
	int offset_x;
	int offset_y;
	long thread_timer = 0;	
	boolean running;
	
	Elf(String filename) {
		this.sprite = SpritePool.get().getSprite(filename);
		elvesTotal++;
	}
	
	public void run() {
		thread_timer = System.nanoTime();
		running = true;
		double delta;
		PathWalker myWalker = Game.get().getMap().getPathWalker(this);
		myWalker.setSpeed(Math.random()*100+150);
		
		while (running) {
			delta = (double)(System.nanoTime() - thread_timer) / 1000000000L;
			Game.get().getMap().updateSingle(myWalker, delta);
			thread_timer = System.nanoTime();			
			try {
				sleep(30);
			} catch (InterruptedException e) { }
		}		
	}

	public void setOffset(int x, int y) {
		this.offset_x = x;
		this.offset_y = y;
	}
	
	public void draw(Graphics2D g, int x, int y) {
		this.sprite.draw(g, x+offset_x, y+offset_y);		
	}
	
	public void kill() {
		this.running = false;
	}
	
	public String toString() {
		return "Elf "+this.getName();
	}
	
	public boolean onEvent(PathWalker p, String event, WayPoint caller, WayPoint helper) {
		if (event.equals("gather")) {
			synchronized (Game.monitor) {
				elvesWaiting++;
				p.setPosition(p.getX()-elvesWaiting*5, p.getY()-elvesWaiting*2);
				do {
					if (Game.get().santa.isSleeping() && elvesWaiting >= elvesNeeded) {
						elvesReleased = true;
						Game.get().santa.wakeUp("Elves");
						Game.monitor.notifyAll();
					} else {
						try {
							Game.monitor.wait();
						} catch (InterruptedException e) { }						
					}					
				} while (!elvesReleased);
				elvesWaiting--;
				if (elvesWaiting == 0) {
					elvesReleased = false;
				}				
			}
			Game.get().getMap().move(p, "Schnee1");			
			return true;
		} else if (event.equals("gate")) {
			if (helper.getName() == "Schnee2") {
				Game.get().getMap().move(p, "Fabrik1");			
			}
		}
		return false;
	}
	
}